<template>
  <div class="add_rec_box">
    <!--     v-dialogDrag -->
    <el-dialog
      close-on-press-escape
      :show-close="false"
      :title="isedit ? '编辑主工艺' : '添加工艺配方'"
      :close-on-click-modal="false"
      :lock-scroll="false"
      :visible="showDialog"
      :width="dw"
      :fullscreen="fullscreen"
      :before-close="handleClose2"
      @close="handleClose"
      @open="handleOpen"
    >
      <!-- 未最小化时的标题栏 -->
      <div slot="title" class="dialog_header">
        <!-- 标题栏左侧标题文字 -->
        <div class="left-title">
          {{ isedit ? "编辑主工艺" : "添加工艺配方" }}
        </div>
        <!-- 标题栏右侧缩小按钮和关闭按钮 -->
        <div class="icons">
          <i
            title="缩小"
            class="i"
            :class="!fullscreen ? 'el-icon-full-screen' : 'el-icon-minus'"
            style="font-size: 24px"
            @click="miniSize"
          />
        </div>
      </div>
      <div class="sele_box w100">
        <el-row :gutter="20" class="w100">
          <el-col :span="12" :offset="0">
            <div class="temp_text">
              <span class="text_title"> 模板选择： </span>
              <el-select
                v-model="form.templateId"
                :disabled="isedit"
                style="width: 100%"
                filterable
                placeholder="请选择"
                size="mini"
                value-key="token"
                @change="templateChange"
              >
                <el-option
                  v-for="item in templateList"
                  :key="item.token"
                  :label="item.name + ' - ' + item.version"
                  :value="item.id"
                >
                  <!-- <span style="float: left"
                >{{ item.name }}-{{ item.version }}
              </span> -->
                </el-option>
              </el-select>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="flex-x flex-top" style="margin-top: 10px">
        <el-form
          id="pointBox"
          ref="formName"
          style="padding: 0 20px"
          class="tab_form"
          label-position="right"
          :model="form"
          :rules="formRules"
          size="mini"
          label-width="auto"
        >
          <el-card
            :ref="newPointList[0].refName"
            class="scroll-item"
            shadow="always"
            :body-style="{ padding: '20px' }"
          >
            <div slot="header">
              <div id="lingjian">零件信息</div>
            </div>
            <el-row type="flex" :gutter="10">
              <el-col :span="6">
                <el-form-item label="零件号:" prop="partNumber">
                  <el-select
                    v-if="parAdditional('零件号').length"
                    :disabled="isedit"
                    v-model="form.partNumber"
                    collapse-tags
                    filterable
                    placeholder="请选择"
                    size="mini"
                    class="w100"
                    @change="partInput(form.partNumber, '零件号')"
                  >
                    <el-option
                      v-for="(item, index) in parAdditional('零件号')"
                      :key="index"
                      :label="item.text"
                      :value="item.text"
                    />
                  </el-select>
                  <Autocomplete
                    v-else
                    :disabled="isedit"
                    v-model="form.partNumber"
                    name="partNumber"
                    placeholder="请输入零件号"
                    @input="partInput(form.partNumber, '零件号')"
                  />
                  <!-- <el-input
                    v-else
                    @input="partInput(form.partNumber, '零件号')"
                    v-model="form.partNumber"
                    placeholder="请输入零件号"
                  ></el-input> -->
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="零件名称:" prop="partName">
                  <el-select
                    v-if="parAdditional('零件名称').length"
                    v-model="form.partName"
                    collapse-tags
                    filterable
                    placeholder="请选择"
                    size="mini"
                    class="w100"
                    @change="partInput(form.partName, '零件名称')"
                  >
                    <el-option
                      v-for="(item, index) in parAdditional('零件名称')"
                      :key="index"
                      :label="item.text"
                      :value="item.value"
                    />
                  </el-select>
                  <Autocomplete
                    v-else
                    v-model="form.partName"
                    name="partName"
                    placeholder="请输入零件名称"
                    @input="partInput(form.partName, '零件名称')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="委托工序号:" prop="entrustProcessNumber">
                  <el-select
                    v-if="parAdditional('委托工序号').length"
                    v-model="form.entrustProcessNumber"
                    :disabled="isedit"
                    collapse-tags
                    filterable
                    placeholder="请选择"
                    size="mini"
                    class="w100"
                    @change="partInput(form.entrustProcessNumber, '委托工序号')"
                  >
                    <el-option
                      v-for="(item, index) in parAdditional('委托工序号')"
                      :key="index"
                      :label="item.text"
                      :value="item.text"
                    />
                  </el-select>
                  <Autocomplete
                    v-else
                    :disabled="isedit"
                    v-model="form.entrustProcessNumber"
                    name="entrustProcessNumber"
                    placeholder="请输入委托工序号"
                    @input="partInput(form.entrustProcessNumber, '委托工序号')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="委托工序名称:" prop="entrustProcessName">
                  <el-select
                    v-if="parAdditional('委托工序名称').length"
                    v-model="form.entrustProcessName"
                    collapse-tags
                    filterable
                    placeholder="请选择"
                    size="mini"
                    class="w100"
                    @change="partInput(form.entrustProcessName, '委托工序名称')"
                  >
                    <el-option
                      v-for="(item, index) in parAdditional('委托工序名称')"
                      :key="index"
                      :label="item.text"
                      :value="item.text"
                    />
                  </el-select>
                  <Autocomplete
                    v-else
                    v-model="form.entrustProcessName"
                    name="entrustProcessName"
                    placeholder="请输入委托工序名称"
                    @input="partInput(form.entrustProcessName, '委托工序名称')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="工序/工步号:" prop="processNumber">
                  <el-select
                    :disabled="isedit"
                    v-if="parAdditional('工序号').length"
                    v-model="form.processNumber"
                    collapse-tags
                    filterable
                    placeholder="请选择"
                    size="mini"
                    class="w100"
                    @change="partInput(form.processNumber, '工序号')"
                  >
                    <el-option
                      v-for="(item, index) in parAdditional('工序号')"
                      :key="index"
                      :label="item.text"
                      :value="item.value"
                    />
                  </el-select>
                  <Autocomplete
                    v-else
                    :disabled="isedit"
                    v-model="form.processNumber"
                    name="processNumber"
                    placeholder="请输入工序号"
                    @input="partInput(form.processNumber, '工序号')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="工序/工步名称:" prop="processName">
                  <el-select
                    v-if="parAdditional('工序名称').length"
                    v-model="form.processName"
                    collapse-tags
                    filterable
                    placeholder="请选择"
                    size="mini"
                    class="w100"
                    @change="partInput(form.processName, '工序名称')"
                  >
                    <el-option
                      v-for="(item, index) in parAdditional('工序名称')"
                      :key="index"
                      :label="item.text"
                      :value="item.value"
                    />
                  </el-select>
                  <Autocomplete
                    v-else
                    v-model="form.processName"
                    name="processName"
                    placeholder="请输入工序名称"
                    @input="partInput(form.processName, '工序名称')"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="材料牌号:" prop="materialMark">
                  <el-select
                    v-if="parAdditional('材料牌号').length"
                    v-model="form.materialMark"
                    collapse-tags
                    filterable
                    placeholder="请选择"
                    size="mini"
                    class="w100"
                    @change="partInput(form.materialMark, '材料牌号')"
                  >
                    <el-option
                      v-for="(item, index) in parAdditional('材料牌号')"
                      :key="index"
                      :label="item.text"
                      :value="item.text"
                    />
                  </el-select>
                  <Autocomplete
                    v-else
                    v-model="form.materialMark"
                    name="materialMark"
                    placeholder="请输入材料牌号"
                    @input="partInput(form.materialMark, '材料牌号')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="工艺版次:" prop="version">
                  <el-select
                    v-if="parAdditional('工艺版次').length"
                    v-model="form.version"
                    collapse-tags
                    filterable
                    placeholder="请选择"
                    size="mini"
                    class="w100"
                    @change="partInput(form.version, '工艺版次')"
                  >
                    <el-option
                      v-for="(item, index) in parAdditional('工艺版次')"
                      :key="index"
                      :label="item.text"
                      :value="item.text"
                    />
                  </el-select>
                  <Autocomplete
                    v-else
                    v-model="form.version"
                    name="version"
                    placeholder="请输入工艺版次"
                    @input="partInput(form.version, '工艺版次')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="工序版次:" prop="processVersion">
                  <Autocomplete
                    v-if="!isedit"
                    v-model="form.processVersion"
                    name="processVersion"
                    placeholder="请输入工艺版次"
                    @input="partInput(form.version, '工序版次')"
                  />
                  <el-select
                    @change="partInput(form.version, '工序版次')"
                    v-else
                    v-model="form.processVersion"
                    value-key=""
                    class="w100"
                    placeholder="请选择/输入"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="item in inputList"
                      :key="item.processVersion"
                      :label="item.processVersion"
                      :value="item.processVersion"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                  <el-form-item label="工步号:" prop="stepNumber">
                    <el-select
                      v-if="parAdditional('工步号').length"
                      v-model="form.stepNumber"
                      collapse-tags
                      filterable
                      placeholder="请选择"
                      size="mini"
                      class="w100"
                      @change="partInput(form.stepNumber, '工步号')"
                    >
                      <el-option
                        v-for="item in parAdditional('工步号')"
                        :key="item.value"
                        :label="item.text"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                    <Autocomplete
                      name="stepNumber"
                      v-else
                      @input="partInput(form.stepNumber, '工步号')"
                      v-model="form.stepNumber"
                      placeholder="请输入工步号"
                    ></Autocomplete>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="工步名称:" prop="stepName">
                    <el-select
                      v-if="parAdditional('工步名称').length"
                      v-model="form.stepName"
                      collapse-tags
                      filterable
                      placeholder="请选择"
                      size="mini"
                      class="w100"
                      @change="partInput(form.stepName, '工步名称')"
                    >
                      <el-option
                        v-for="item in parAdditional('工步名称')"
                        :key="item.value"
                        :label="item.text"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                    <Autocomplete
                      name="stepName"
                      v-else
                      @input="partInput(form.stepName, '工步名称')"
                      v-model="form.stepName"
                      placeholder="请输入工步名称"
                    ></Autocomplete>
                  </el-form-item>
                </el-col> -->

              <el-col :span="6">
                <el-form-item label="有效期:" prop="youxiaoqi">
                  <el-date-picker
                    v-model="form.youxiaoqi"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :picker-options="expireTimeOption"
                    type="datetimerange"
                    class="w100"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="状态:" prop="state">
                  <el-radio v-model="form.state" label="true">可用</el-radio>
                  <el-radio v-model="form.state" label="false">禁用</el-radio>
                </el-form-item>
              </el-col>

              <div v-if="form.technologyParameter.length" class="w100">
                <el-col
                  v-for="(item, index) in form.technologyParameter"
                  :key="item.key"
                  :span="6"
                >
                  <el-form-item
                    v-if="
                      !sparePartsList.includes(item.key) &&
                        item.type != 5 &&
                        item.type != 6
                    "
                    :prop="'technologyParameter.' + index + '.val'"
                    :rules="[
                      {
                        required: item.required,
                        message: item.key + '不能为空',
                        trigger: 'blur'
                      }
                    ]"
                    :label="item.key + ':'"
                  >
                    <el-select
                      v-if="item.additional.length"
                      v-model="item.val"
                      collapse-tags
                      filterable
                      placeholder="请选择"
                      size="mini"
                      :disabled="item.disabled"
                      class="w100"
                    >
                      <el-option
                        v-for="item in item.additional"
                        :key="item.value"
                        :label="item.text"
                        :value="item.value"
                      />
                    </el-select>
                    <el-input
                      v-else
                      v-model="item.val"
                      :disabled="item.disabled"
                      :placeholder="item.value"
                    />
                  </el-form-item>
                </el-col>
              </div>
            </el-row>
          </el-card>
          <!-- v-if="!isedit" -->
          <el-card
            :ref="newPointList[1].refName"
            class="scroll-item"
            shadow="always"
            :body-style="{ padding: '20px' }"
            style="margin-top: 10px"
          >
            <div slot="header">
              <div id="jiare">加热参数</div>
            </div>
            <el-row type="flex" :gutter="10">
              <el-col :span="24" :offset="0">
                <Equipment
                  ref="equipmentRef"
                  :device-info-list-model="deviceInfoListModel"
                  :treedata="treedata"
                  style="margin-top: 10px"
                />
              </el-col>

              <el-col
                v-if="formulaParameter && formulaParameter.length !== 0"
                :span="24"
                justify="end"
              >
                <!-- <el-form-item
                    style="
                      display: flex;
                      justify-content: flex-end;
                      margin-top: 20px;
                    "
                  >

                  </el-form-item> -->
                <FormulaTabel
                  style="margin-top: 20px;"
                  :tableData="formulaTable"
                  :columns="formulaParameter"
                ></FormulaTabel>
              </el-col>
            </el-row>
          </el-card>
        </el-form>
      </div>

      <div v-if="isedit" slot="footer" class="dialog-footer">
        <el-button :loading="btnLoading" size="mini" @click="handleCloseBtn"
          >取 消</el-button
        >
        <el-button
          :loading="btnLoading"
          size="mini"
          type="primary"
          @click="submitForm('formName')"
          >确 定</el-button
        >
      </div>
      <div v-else slot="footer" class="dialog-footer">
        <el-button :loading="btnLoading" size="mini" @click="handleCloseBtn"
          >取 消</el-button
        >
        <el-button
          :loading="btnLoading"
          size="mini"
          type="primary"
          @click="submitForm('formName')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
//合并相同
export function unique(arr) {
  if (!Array.isArray(arr)) {
    console.log("type error!");
    return;
  }
  let newData = JSON.parse(JSON.stringify(arr));
  for (var i = 0; i < newData.length; i++) {
    if (!newData[i].list) {
      newData[i].list = [
        {
          ...newData[i]
        }
      ];
    }
    for (var j = i + 1; j < newData.length; j++) {
      if (
        newData[i].device.deviceType.token == newData[j].device.deviceType.token
      ) {
        newData[i].list.push(newData[j]);
        newData.splice(j, 1);
        j--;
      } else {
      }
    }
  }

  return newData;
}
import FormulaTabel from "./FormulaTabel.vue";
import Autocomplete from "@/components/Autocomplete";
import { spareParts } from "@/utils/local";
import {
  getTechnology,
  submitFormula,
  getFormulaToken,
  editFormula,
  getFormulass
} from "@/api/technology";
import { generateId } from "@/utils/index";
import { getDeviceTypesV2, getDeviceTypes } from "@/api/deviceType";
import _ from "lodash";
import { VERSION_RULES } from "@/utils/local";
import MyCascader from "./Cascader.vue";
import Equipment from "./Equipment.vue";
import moment from "moment";
import { parseTime } from "@/utils/parseTime";
import { mapGetters } from "vuex";
import { currentDate3 } from "@/utils/currentDate";
import { getAssignmentSearchList } from "@/api/assignments";
let that = null;
export default {
  components: {
    Autocomplete,
    // MetaData,
    MyCascader,
    Equipment,
    FormulaTabel
  },
  props: {
    showDialog: {
      type: Boolean,
      default: true
    },
    isTechnoNavto: {
      type: Boolean,
      default: false
    },
    token: {
      type: String,
      default: ""
    },
    isedit: {
      type: Boolean,
      default: false
    },
    templateList: {
      type: Array,
      default: () => []
    }
  },

  data() {
    return {
      manufactureSiteToken: "", //站点token
      expireTimeOption: {
        disabledDate(time) {
          const dateTime = new Date();
          const startDateTime = dateTime.setDate(dateTime.getDate() - 1);
          return time.getTime() < new Date(startDateTime).getTime();
        },
        selectableRange:
          parseTime(
            new Date(moment().format("YYYY-MM-DD HH:mm:ss")),
            "{hh}:{ii}:{ss}"
          ) + "- 23:59:59"
      },
      tabName: "lingjian",
      sparePartsList: spareParts,
      versionList: [],
      deviceInfo: [],
      treedata: [],
      processList: [],
      props: { multiple: true, value: "token", label: "name" },
      dw: "80%",
      fullscreen: true,
      attributes: [],
      // templateList: [],
      activeName: "first",
      btnLoading: false,
      tabPosition: "left",
      formulaParameter: [],
      formulaTable: [],
      technologyList: [],
      editmetaData: {},
      technologyParameterLength: 0, // 记录初始的长度,删除匹配到的表格下方单元数量
      technologyParameterIds: [],
      devicetypesTypes: [],
      deviceInfoListModel: [],
      inputList: [],
      form: {
        entrustProcessNumber: "", // 委托工序号
        entrustProcessName: "", // 委托工序名称
        materialMark: "", // 材料牌号
        stepNumber: "",
        stepName: "",
        processVersion: "",
        partName: "",
        processName: "",
        processNumber: "",
        partNumber: "",
        startDate: "",
        endDate: "",
        deviceInfoList: [],
        isTermValidity: [],
        youxiaoqi: "",
        state: "false",
        templateId: "",
        author: "",
        url: "",
        name: "",
        version: "",
        version1: "",
        technologyId: "", // 主工艺id
        technologyParameter: [], // 自定义的 工艺变量
        formulaParameter: [],
        metadata: {}
      },
      formRules: {
        entrustProcessNumber: [{ required: true, message: "请输入委托工序号" }],
        entrustProcessName: [{ required: true, message: "请输入委托工序名称" }],
        materialMark: [{ required: true, message: "请输入材料牌号" }],
        processNumber: [{ required: true, message: "请输入工序号" }],
        processName: [{ required: true, message: "请输入工序名称" }],
        state: [{ required: true, message: "请选择状态" }],
        version: VERSION_RULES,
        partNumber: [{ required: true, message: "请输入零件号" }],
        partName: [{ required: true, message: "请输入零件名称" }],
        processVersion: [{ required: true, message: "请输入工序版次" }]
        // stepName: [{ required: true, message: "请输入工步名称" }],
        // stepNumber: [{ required: true, message: "请输入工步号" }],
        // partNumber: [
        //   { required: true, message: "请输入零件号", trigger: "blur" },
        // ],
        // processNumber: [
        //   { required: true, message: "请输入工序号", trigger: "blur" },
        // ],
        // deviceList: [
        //   { required: true, message: "请选择设备", trigger: "change" },
        // ],
        // deviceTypeToken: [
        //   { required: true, message: "请选择设备类型", trigger: "change" },
        // ],
      }
    };
  },
  computed: {
    ...mapGetters(["manufactureSiteList"]),
    newPointList() {
      return [
        {
          name: "零件信息",
          refName: "lingjian"
        },

        {
          name: "加热参数",
          refName: "jiare"
        }
      ];
      // const arr = this.isedit
      //   ? [
      //       {
      //         name: "零件信息",
      //         refName: "lingjian",
      //       },
      //     ]
      //   : [
      //       {
      //         name: "零件信息",
      //         refName: "lingjian",
      //       },

      //       {
      //         name: "加热参数",
      //         refName: "jiare",
      //       },
      //     ];
      // return arr;
    },
    parAdditional() {
      return function(key = "零件号") {
        const obj = this.form.technologyParameter.find(item => {
          return item.key == key && item.additional.length !== 0;
        });
        return obj?.additional || [];
      };
    },
    technologyListUniqBy() {
      return _.uniqBy(
        this.technologyList.map(item => {
          return {
            ...item,
            label: item["partNumber"],
            value: item["partNumber"]
          };
        }),
        "partNumber"
      );
    },
    processListUniqBy() {
      return _.uniqBy(
        this.processList.map(item => {
          return {
            ...item,
            label: item["processNumber"],
            value: item["processNumber"]
          };
        }),
        "processNumber"
      );
    },
    versionListUniqBy() {
      return _.uniqBy(
        this.versionList.map(item => {
          return {
            ...item,
            label: item["version"],
            value: item["version"]
          };
        }),
        "version"
      );
    },
    // ...mapGetters(["tenant"]),
    tenant() {
      return this.$store.state.user.tenant;
    },
    generateId() {
      return generateId();
    },
    // username() {
    //   return getCookie("user").username;
    // },
    username() {
      return this.$store.state.user.user.username;
    }
  },
  watch: {
    // 禁用此刻之前所有时间
  },
  created() {
    that = this;
  },
  mounted() {},

  methods: {
    getFormulass() {
      getFormulass({
        technologyId: this.form.id,
        includeTemplate: true,
        includeTechnology: true
      }).then(res => {
        this.inputList = res.data.results;
      });
    },

    lazyLoad(data) {
      this.form.technologyId = data.id;
      this.form.reportId = data.reportId;
    },
    partInput(val, key) {
      this.form.technologyParameter.forEach(item => {
        if (item.key == key) {
          item.val = val;
        }
      });
    },
    getdevicetypesTypes() {
      return new Promise((resolve, reject) => {
        getDeviceTypesV2({ page: 1, pageSize: 200000 }).then(res => {
          const { results } = res.data;
          this.devicetypesTypes = results;
          resolve(this.devicetypesTypes);
        });
      });
    },
    miniSize() {
      this.fullscreen = !this.fullscreen;
    },
    setdeviceInfoList(arr) {
      const newArr = [];
      arr.forEach(item => {
        item.deviceList.forEach(dev => {
          newArr.push([item.deviceTypeToken, dev.deviceToken]);
        });
      });
      this.deviceInfo = newArr;
    },
    // 弹窗打开执行操作
    async handleOpen() {
      this.formulaTable = [];
      this.formulaParameter = [];
      this.fullscreen = true;
      // this.form = {};
      this.$nextTick(() => {
        if (this.$refs.myCascaderRef) {
          this.$refs.myCascaderRef.addressArr = [];
        }
        if (!this.isTechnoNavto) {
          Object.assign(this.$data.form, this.$options.data().form);
          this.form.technologyParameter = [];
          this.technologyList = [];
          // this.treedata = []; //设备不能清空-会报一个无法找到默认选项的错误
          this.deviceInfo = [];
          this.processList = [];
          this.formulaParameter = [];
          this.devicetypesTypes = [];
          // this.$refs["metaDataRef"].clearMeteDada();
          this.$refs["formName"].clearValidate();
          this.$refs["formName"].resetFields();
          this.activeName = "first";
          this.deviceInfoListModel = [];
          // await this.getTemplateList();

          // this.isedit = true;
          if (this.isedit) {
            this.init();
          } else {
            // this.getTree();
            // this.getTechnologyList();
          }
        }

        this.form.author = this.username;
      });
      // await this.getdevicetypesTypes();
    },
    // 获取 (详情)
    async init() {
      // var params = {
      //   page: 1,
      //   pageSize: 0,
      // };
      // const logy = await getTechnology(params);

      // const { results } = logy.data;
      // this.technologyList = results;

      getFormulaToken(this.token, false, true).then(async res => {
        const { data } = res;
        const {
          metadata,
          technologyParameter,
          formulaParameter,
          partNumber,
          technologyId,
          templateId,
          startDate,
          endDate,
          deviceInfoList,
          technology
        } = data;
        // this.treedata = this.useTree(deviceInfoList);
        this.deviceInfoListModel = deviceInfoList;

        this.form = data;
        this.getFormulass();
        // this.setdeviceInfoList(deviceInfoList);
        // 设备
        // technologyList form.technologyId
        // this.devicetypesTypesChange(data.deviceTypeToken);
        // 获取模板下的 工艺变量
        const tempObj = this.templateList.find(item => item.id === templateId);
        const tempTechnologyParameter = tempObj.technologyParameter;
        this.manufactureSiteToken =
          this.manufactureSiteList.find(
            item => item.name == tempObj.manufactureSite
          )?.token || "";
        this.getTree();
        this.form.technologyParameter = technology.technologyParameter.map(
          item => {
            if (item.key === "零件名称") {
              this.form.partName = item.value;
            }
            if (item.key === "工序名称") {
              this.form.processName = item.value;
            }
            tempTechnologyParameter.forEach(temp => {
              if (temp.key === item.key) {
                item.required = temp.required;
              }
            });
            return {
              ...item,
              v: item.value,
              val: item.value,
              disabled: spareParts.includes(item.key)
            };
          }
        );
        // const logList = await this.getTechnologyList(templateId);
        // 此处拿到的是零件id 从新获取到零件号 在去获取工序号
        // this.getProcessList(partNumber);

        const youxiaoqi = startDate && endDate ? [startDate, endDate] : [];
        this.$set(this.form, "youxiaoqi", youxiaoqi);
        // this.form.technologyParameter =
        //   this.technologyList.find((item) => item.id == technologyId)
        //     ?.technologyParameter || [];

        // this.technologyParameterIds = technologyParameter.map(
        //   (item) => item.key
        // );
        // 获取模板下的原始配方参数
        const formulaParameterArr =
          this.templateList.find(item => item.id == templateId)
            ?.formulaParameter || [];

        // 拼接成 竖表格可识别参数

        if (formulaParameter) {
          if (formulaParameter.length == 0) {
            // this.technologyParameterLength = deviceInfoList.length;
            this.templateChange(templateId);
          } else {
            formulaParameter.forEach(item => {});

            this.formulaParameter = formulaParameterArr;

            this.formulaTable = formulaParameter.map(item => {
              let obj = {};
              item.keys.forEach((key, index) => {
                obj[key] = item.values[index];
              });
              return obj;
            });
          }
        }
      });
    },

    // 设置最终提交的参数
    setSubArr() {
      let arr = [];
      this.formulaTable.forEach((item, index) => {
        // keys ,orderNum,texts,types,values
        let keys = Object.keys(item);
        let texts = [];
        let types = [];
        keys.forEach(key => {
          texts.push(item[key]);
          types.push(
            this.formulaParameter.find(f => f.key == key)?.type || "1"
          );
        });
        arr.push({
          keys,
          texts,
          values: texts,
          types,
          orderNum: index + 1
        });
      });
      return arr;
    },
    // 提交
    submitForm(formName) {
      // this.form.deviceInfoList = this.useDevList(
      //   this.$refs.equipmentRef.tabData
      // );
      // console.log(" this.form.deviceInfoList :>> ", this.form.deviceInfoList);
      // if (time > now) {
      //   this.isYouxiaoqi = true;
      // }
      this.form.formulaParameter = this.setSubArr();
      console.log(
        "this.form.formulaParameter  :>> ",
        this.form.formulaParameter
      );
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (!this.form.templateId) {
            this.$msg("请选择模板");
            return;
          }

          this.form.technologyParameter = this.form.technologyParameter.map(
            item => {
              return {
                ...item,
                value: item.val,
                text: item.val
              };
            }
          );
          // if (!this.isedit) {
          //   // this.form.partNumber = this.$refs.myCascaderRef.addressArr[0];
          //   // this.form.processNumber = this.$refs.myCascaderRef.addressArr[1];
          //   // this.form.version = this.$refs.myCascaderRef.addressArr[3];
          // }
          let isYouxiaoqi = true;
          try {
            if (this.form.youxiaoqi && this.form.youxiaoqi.length) {
              const myDate = this.$moment(new Date()).format(
                "YYYY-MM-DD H:mm:ss"
              );
              const now = myDate.valueOf();
              const time = this.form.youxiaoqi[0].valueOf();
              isYouxiaoqi = time > now;
              this.form.startDate = currentDate3(this.form.youxiaoqi[0]);
              this.form.endDate = currentDate3(this.form.youxiaoqi[1]);
            } else {
              this.form.startDate = "";
              this.form.endDate = "";
            }
            if (!isYouxiaoqi) {
              this.$msg("有效期开始时间不得小于当前时间");
              return;
            }
            if (this.$refs.equipmentRef.tabData.length == 0) {
              this.$msg("请选择设备");
              return;
            }
            // this.setFormulaParameter();
            this.form.deviceInfoList = this.useDevList(
              this.$refs.equipmentRef.tabData
            );
            if (this.isedit) {
              // console.log("  this.form :>> ", this.form);
              this.btnLoading = true;
              editFormula(this.form, this.token)
                .then(async res => {
                  this.$msg({
                    type: "success",
                    message: "修改成功"
                  });
                  this.handleClose(true, res.data.token);
                })
                .catch(err => {
                  console.log(err, "response");
                  if (
                    err &&
                    err.response &&
                    err.response.data ==
                      "DuplicateTechnologyFormula:Technology formula token already in use."
                  ) {
                    this.$msg("token重复,请从新选择零件号和工序号");
                  }
                })
                .finally(f => {
                  this.btnLoading = false;
                });
            } else {
              if (this.formulaParameter.length == 0) {
                this.$msg("没有模板参数!");
                return;
              }
              this.btnLoading = true;
              this.form.token =
                this.form.partNumber +
                "_" +
                this.form.processNumber +
                "_" +
                this.form.version;
              submitFormula(this.form)
                .then(async res => {
                  // await save2pdf(this.form.url);
                  console.log("提交", res);
                  this.$msg({
                    type: "success",
                    message: "提交成功"
                  });
                  this.handleClose(true, this.form.token);
                })
                .catch(err => {
                  console.log(err.response, "response");
                  if (
                    err &&
                    err.response &&
                    err.response.data ==
                      "DuplicateTechnologyFormula:Technology formula token already in use."
                  ) {
                    this.$msg("token重复,请从新选择零件号和工序号");
                  }
                })
                .finally(f => {
                  this.btnLoading = false;
                });
            }
            // })
          } catch (error) {
            this.$msg("error:" + error);
            this.btnLoading = false;
          }
        } else {
          this.$msg("请完善必填信息!");
        }
      });
    },
    useDevList(arr) {
      arr = unique(arr);
      return arr.map(item => {
        const deviceList = item.list.map(li => {
          return {
            deviceName: li.device.name,
            deviceToken: li.device.token,
            feedCount: li.feedCount,
            tailCount: li.tailCount,
            partCount: li.partCount,
            description: li.description,
            toolingCount: li.toolingCount,
            toolingName: li.toolingName
          };
        });
        return {
          deviceTypeName: item.device.deviceType.name,
          deviceTypeToken: item.device.deviceType.token,
          deviceList: deviceList,
          feedCount: item.feedCount,
          tailCount: item.tailCount,
          partCount: item.partCount,
          description: item.description,
          toolingCount: item.toolingCount,
          toolingName: item.toolingName
        };
      });
    },

    // 工序
    processChange(val) {
      // form.technologyId technologyParameter
      const obj = this.processList.find(item => item.id == val);
      // console.log("obj :>> ", obj);
      if (obj) {
        this.form.processNumber = obj.processNumber;
        this.form.technologyParameter = obj.technologyParameter;
      }

      getTechnology({
        page: 1,
        pageSize: 0,
        partNumber: this.form.partNumber,
        processNumber: this.form.processNumber
      }).then(res => {
        const { results } = res.data;
        this.versionList = results;
      });
    },
    // 获取树状列表
    async getTree() {
      // this.manufactureSiteToken
      var rn =
        "includeDevice=true&includeCustomer=true&includeArea=true&includeAsset=true&userIds=";
      // this.manufactureSiteToken
      var param = {
        areaTokens: [this.manufactureSiteToken]
      };
      getAssignmentSearchList(param, rn).then(res => {
        this.treedata = res.data.results.map(item => {
          return {
            ...item.ideviceAssignment
            // ...item.user
          };
        });
        console.log("res :>> ", this.treedata);
      });
      // const that = this;
      // // const res = await getDevicesV2Tree();
      // const res = await getDeviceTypes();
      // const { data } = res;
      // console.log(data);
      // that.treedata = [...data.results];
    },
    useTree(arr) {
      const arr2 = [];
      tree(arr);
      function tree(arr) {
        arr.forEach(item => {
          if (item.type == 2) {
            arr2.push(item);
          } else if (item.children && item.children.length !== 0) {
            tree(item.children);
          }
        });
      }
      return arr2;
    },
    // 获取工序
    getProcessList(partNumber, processNumber) {
      var params = {
        page: 1,
        pageSize: 0,
        partNumber
      };
      getTechnology(params).then(res => {
        const { results } = res.data;

        this.processList = results;
        // 如果传入工序号-就赋值id
        if (processNumber) {
          this.form.processNumber = processNumber;
        }
      });
    },
    // 选择零件
    technologChange(val) {
      this.form.technologyId = "";
      this.processList = [];
      const obj = this.technologyList.find(item => item.partNumber == val);

      const { url } = obj;
      this.getProcessList(val);
      this.form.url = url;

      if (!this.isTechnoNavto) return;
      this.$nextTick(() => {
        this.$refs.techRef.focus();
      });
    },
    // 选择模板
    templateChange(val) {
      // this.getTechnologyList(val);
      // templateId
      const obj = this.templateList.find(item => item.id == val);

      if (!obj) return;
      // 获取制造单元token
      this.manufactureSiteToken =
        this.manufactureSiteList.find(item => item.name == obj.manufactureSite)
          ?.token || "";
      // 获取树结构
      console.log("是否存在站点 :>> ", this.manufactureSiteToken, val);
      this.getTree();
      this.form.technologyParameter = obj.technologyParameter.map(item => {
        let val = "";
        spareParts.forEach(spa => {
          if (spa == item.key) {
            val = this.form.partNumber;
          }
        });
        return {
          ...item,
          v: item.key,
          val: val,
          disabled: spareParts.includes(item.key)
        };
      });
      // 赋值 积木id
      this.form.reportId = obj.reportId;
      console.log("obj ", obj);
      this.formulaParameter = obj.formulaParameter;
    },

    // 获取模板列表
    // getTemplateList() {
    //   return new Promise((resolve, reject) => {
    //     var params = {
    //       page: 1,
    //       pageSize: 0,
    //     };
    //     getTemplate(params).then((res) => {
    //       const { results } = res.data;
    //       this.templateList = results;
    //       resolve();
    //     });
    //   });
    // },

    // 获取主工艺(零件)
    getTechnologyList(templateId) {
      return new Promise((resolve, reject) => {
        var params = {
          page: 1,
          pageSize: 0,
          templateId
        };
        getTechnology(params).then(res => {
          const { results } = res.data;
          this.technologyList = results.filter((ele, index, arr) => {
            return (
              arr.findIndex(item => item.partNumber === ele.partNumber) ===
              index
            );
          });
          // 手动清空级联
          if (!this.isedit) {
            this.$refs.myCascaderRef.addressArr = [];
            // this.$refs.myCascaderRef.province = [{}];
            // 从新渲染级联
            this.$refs.myCascaderRef.is_cascader = Math.random();
            this.$refs.myCascaderRef.province = this.technologyList.map(
              item => {
                return {
                  ...item,
                  label: item.partNumber,
                  value: item.partNumber
                };
              }
            );
          }

          resolve(this.technologyList);
        });
      });
    },
    handleCloseBtn() {
      if (this.btnLoading) {
        return;
      } else {
        this.handleClose();
      }
    },
    // 弹窗关闭执行操作
    handleClose2(done) {
      if (this.btnLoading) {
        return;
      } else {
        done();
      }
    },
    handleClose(isRefresh, token) {
      // this.$refs["formName"].clearValidate();
      // this.$refs["formName"].resetFields();
      this.$emit("update:showDialog", false);
      this.$emit("closeDialog", isRefresh, token);
      Object.assign(this.$data.form, this.$options.data().form);
      this.cancelEmpty();
    },
    // 取消清空数据
    cancelEmpty() {},

    // 元数据页回传
    sendmetaData(data) {
      this.form.metadata = data;
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.tab_heng {
  // padding-top: 0.625rem;
  max-width: 100%;
}

.check_box {
  background-color: #f8f8fb;
  padding: 5px 20px;
  margin-bottom: 0.625rem;

  .check_item {
    padding: 5px 0;
    width: 140px;

    /deep/ .el-checkbox {
      @include textoverflow(1);
    }
  }
}

.tab_form {
  padding-top: 1.25rem;
  // max-height: 56vh;
  overflow: hidden;
  overflow-y: auto;
  padding-right: 10px;

  .el-row--flex {
    flex-wrap: wrap;
  }
}

.svg-icon {
  cursor: pointer;
  margin-bottom: 0.3125rem;
}

.add_rec_box {
  .dialog_header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;

    .icons {
      cursor: pointer;
    }
  }

  .sele_box {
    display: flex;
    align-items: center;
    background-color: #f9f9f9;
    padding: 10px 30px 10px 120px;

    .temp_text {
      display: flex;
      align-items: center;

      .text_title {
        white-space: nowrap;
      }
    }
  }

  /deep/ .el-dialog__body {
    padding-top: 0;
    padding-left: 0;
    padding-right: 0;

    /* 解决级联选择之后页面抖动问题(element内部自适应造成的高度一直变化) */
    .el-cascader__tags {
      @include textoverflow(1);
    }

    .el-cascader--mini .el-input__inner {
      height: 28px !important;
    }
  }
}
</style>
